package pers.cloud.ocr.tencent;

import com.qcloud.image.ImageClient;
import com.qcloud.image.exception.AbstractImageException;
import com.qcloud.image.request.IdcardDetectRequest;
import com.qcloud.image.sign.Credentials;
import org.json.JSONObject;
import pers.cloud.ocr.tencent.config.TencentORCConfig;
import pers.cloud.ocr.tencent.model.IDCard;
import pers.cloud.orc.throwable.MyCloudOCRException;

import java.io.File;


public class TencentORC {

    private TencentORCConfig tencentORCConfig;
    public TencentORC(TencentORCConfig tencentORCConfig) {
        this.tencentORCConfig = tencentORCConfig;
    }

    public IDCard orcIdCard(File idCardFile) throws AbstractImageException {
        ImageClient imageClient = new ImageClient(new Credentials(String.valueOf(tencentORCConfig.getAppId()),tencentORCConfig.getSecretId(),tencentORCConfig.getSecretKey()));
        File[] files = new File[1];
        files[0] = idCardFile;
        IdcardDetectRequest  idReq = new IdcardDetectRequest("", files, 0);
        //请求并对返回值进行封装
        JSONObject jsonObject = new JSONObject(imageClient.idcardDetect(idReq))
                .getJSONArray("result_list")
                .getJSONObject(0).getJSONObject("data");
        IDCard idCard = new IDCard();
        idCard.setAddress((String) jsonObject.get("address"));
        idCard.setBirthday((String) jsonObject.get("birth"));
        idCard.setName((String) jsonObject.get("name"));
        idCard.setIdCardNumber((String) jsonObject.get("id"));
        idCard.setNation((String) jsonObject.get("nation"));
        idCard.setSex((String) jsonObject.get("sex"));
        return idCard;
    }

    public static void main(String[] args) throws MyCloudOCRException, AbstractImageException {
        TencentORC tencentORC = new TencentORC(new TencentORCConfig.Builder()
                .addAppId(10009732).addSecretId("AKID8DrZORhmNjQ3heaB7gWo7h0fpDTyQMQs")
                .addSecretKey("SskkB5EicO0lRTqTF1EDm5JHZXEEvzQS")
                .build());
        File file = new File("C:\\Users\\54768\\Pictures\\2.jpg");
        System.out.println(tencentORC.orcIdCard(file).toString());
    }
}
